/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

.controller('TruckDetailCtrl', ['$rootScope', '$scope', '$state', 'UserTruckService', function ($rootScope, $scope, $state, UserTruckService) {
    var truckId = $state.params.truckId;
    var driverId = $state.params.driverId;

    $scope.truckData = null;
    $scope.driverData = null;
    // 审核用户车辆信息
    $scope.audit = function (status, truckType) {
        UserTruckService.audit(truckId, driverId, status, truckType)
            .success(function (result) {
                if (result.success) {
                    $state.go("user-truck");
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }

    $scope.picData = {
        title: "车辆、证照、身份证", //相册标题
        id: driverId, //相册id
        start: 0, //初始显示的图片序号，默认0
        data: []   //相册包含的图片，数组格式
    };

    var num = 0;

    // 初始化车辆信息
    function loadTruckData(truckId) {
        if (truckId) {
            UserTruckService.truckDetail(truckId)
                .success(function (result) {
                    if (result.success) {
                        $scope.truckData = result.data;
                        if (result.data.jsMap) {
                            buildData(result.data.jsMap);
                        }
                        if (result.data.xsMap) {
                            buildData(result.data.xsMap);
                        }
                        if (result.data.dlMap) {
                            buildData(result.data.dlMap);
                        }
                        if (result.data.qyMap) {
                            buildData(result.data.qyMap);
                        }
                        if (result.data.gcMap) {
                            buildData(result.data.gcMap);
                        }
                    } else {
                        $rootScope.hycadmin.toast({
                            title: result.message,
                            timeOut: 3000
                        });
                    }
                })
        }
    }

    // 初始化司机信息
    function loadDriverData(driverId) {
        if (driverId) {
            UserTruckService.driverDetail(driverId)
                .success(function (result) {
                    if (result.success) {
                        $scope.driverData = result.data;
                        $scope.picData.data.push({
                            alt: "身份证正面照片",
                            pid: 10, //图片id
                            src: $scope.driverData.idpic1, //原图地址
                            thumb: $scope.driverData.idpic1 + "?imageView2/2/h/150" //缩略图地址
                        });
                        $scope.picData.data.push({
                            alt: "身份证反面照片",
                            pid: 11, //图片id
                            src: $scope.driverData.idpic2, //原图地址
                            thumb: $scope.driverData.idpic2 + "?imageView2/2/h/150" //缩略图地址
                        });
                    } else {
                        $rootScope.hycadmin.toast({
                            title: result.message,
                            timeOut: 3000
                        });
                    }
                })
        }
    }

    $scope.num = 0;
    function buildData(data) {
        $scope.picData.data.push({
            alt: data.desc,
            pid: num, //图片id
            src: data.url, //原图地址
            thumb: data.url + "?imageView2/2/h/150" //缩略图地址
        });
        num++;
    }

    // 查看大图
    $scope.showPhones = function (index) {
        layer.photos({
            photos: angular.extend($scope.picData, {start: (index || 0)})
        });
    };

    loadTruckData(truckId);
    loadDriverData(driverId);
}])

.controller('TmsAgingCtrl', ['$rootScope', '$scope', 'TmsAdminService', function ($rootScope, $scope, TmsAdminService) {
    $scope.searchObj = {
        startDate: null,
        endDate: null,
        status: null
    };

    $scope.statusList = [{
        label: '待发车',
        value: 5
    }, {
        label: '在途',
        value: 10
    }, {
        label: '已交车',
        value: 20
    }, {
        label: '已完成',
        value: 30
    }, {
        label: '未回单',
        value: 40
    }];

    $scope.list = [];

    $scope.clearQuery = function () {
        $scope.searchObj.startDate = null;
        $scope.searchObj.endDate = null;
        $scope.searchObj.status = null;
        $scope.loadData();
    };

    $scope.loadData = function () {
        TmsAdminService.aging({
            startDate: $scope.searchObj.startDate ? $scope.searchObj.startDate.format($scope.searchObj.startDate.YYYY_MM_DD) : null,
            endDate: $scope.searchObj.endDate ? $scope.searchObj.endDate.format($scope.searchObj.endDate.YYYY_MM_DD) : null,
            status: $scope.searchObj.status
        })
            .success(function (result) {
                  if (result.success) {
                      $scope.list = result.data;
                  }
            })
    };

    // 初始化
    $scope.loadData();
}])

.controller('TMSDamageWaybillCtrl', ['$rootScope', '$scope', '$modal', 'TMSWaybillService', function ($rootScope, $scope, $modal, TMSWaybillService) {
    // 查询条件
    $scope.waybill = {
        orderCode: ''
    };

    // 数据列表
    $scope.waybillList = [];

    // 图片列表
    $scope.picList = [];


    var picPreviewModal = $modal({scope: $scope, title: '图片预览', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/components/tms-damage-pic-view.html', show: false});

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        TMSWaybillService.damageList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            orderCode: $scope.waybill.orderCode
        }).success(function (result) {
            if (result.success) {
                $scope.waybillList = result.data.waybillList;
                angular.forEach($scope.waybillList, function (item) {
                    item.waybillStatusText = Tools.getDWaybillStatusText(item.waybillStatus);
                    //item.damageText = Tools.getDWaybillDamageStatusText(item.damageAudit);
                });
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.waybill = {
            orderCode: ''
        };
        $scope.loadData('load');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 审核
    $scope.audit = function (waybill, status) {
        TMSWaybillService.damageAudit({
            waybillId: waybill.id,
            status: status
        }).success(function (result) {
            if (result.success) {
                $rootScope.hycadmin.toast({
                    title: '审核成功',
                    timeOut: 3000
                });
                $scope.loadData('load');
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 图片预览
    $scope.listPic = function (waybill) {
        TMSWaybillService.listPic({
            waybillId: waybill.id
        }).success(function (result) {
            if (result.success) {
                $scope.picList = result.data;
                picPreviewModal.$promise.then(picPreviewModal.show);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 初始化数据
    $scope.loadData('load');
}])

.controller('TMSWaybillCtrl', ['$rootScope', '$scope', 'TMSWaybillService', function ($rootScope, $scope, TMSWaybillService) {
    // 查询条件
    $scope.waybill = {
        orderCode: ''
    };

    $scope.waybillObj = {
        waybillList: [],
        tabs:[{
                id: 'tab1',
                name: '待配单',
                isActive: true,
                status: Tools.getDWaybillStatus.getSave()
            },
            {
                id: 'tab2',
                name: '待发运',
                isActive: false,
                status: Tools.getDWaybillStatus.getDeparture()
            },
            {
                id: 'tab3',
                name: '在途中',
                isActive: false,
                status: Tools.getDWaybillStatus.getIntransit()
            },
            {
                id: 'tab4',
                name: '已交车',
                isActive: false,
                status: Tools.getDWaybillStatus.getDealCar()
            },
            {
                id: 'tab5',
                name: '已完成',
                isActive: false,
                status: Tools.getDWaybillStatus.getCompleted()
            },
            {
                id: 'tab6',
                name: '已取消',
                isActive: false,
                status: Tools.getDWaybillStatus.getCancel()
            }
        ],
        initData: function () {
            $scope.loadData('load');
        }
    };

    // tab索引
    var indexOf = 0;

    // 是否显示操作列
    $scope.isOption = false;

    // 切换tab
    $scope.checkTab = function (tab, index) {
        indexOf = index;
        angular.forEach($scope.waybillObj.tabs, function (item) {
            if (item.id === tab.id) {
                item.isActive = true;
                $scope.userTruckObj.pageNo = 1;
                $scope.userTruckObj.pageSize = 10;
                $scope.page.pageNo = 1;
                $scope.page.totalPage = 0;
                // 设置操作列是否可见
                if (tab.status === Tools.getDWaybillStatus.getDeparture()) {
                    $scope.isOption = true;
                } else {
                    $scope.isOption = false;
                }
                $scope.waybillObj.initData();
            } else {
                item.isActive = false;
            }
        });
    };

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        TMSWaybillService.tmsList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            orderCode: $scope.waybill.orderCode,
            waybillStatus: $scope.waybillObj.tabs[indexOf].status
        }).success(function (result) {
            if (result.success) {
                $scope.waybillObj.waybillList = result.data.waybillList || [];
                angular.forEach($scope.waybillObj.waybillList, function (item) {
                    item.waybillStatusText = Tools.getDWaybillStatusText(item.waybillStatus);
                });
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.waybill = {
            orderCode: ''
        };
        $scope.loadData('load');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 退单
    $scope.quit = function (waybill) {
        TMSWaybillService.cancel({
            waybillId: waybill.id
        }).success(function (result) {
            if (result.success) {
                $rootScope.hycadmin.toast({
                    title: '退单成功',
                    timeOut: 3000
                });
                $scope.loadData('load');
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 初始化数据
    $scope.waybillObj.initData();
}])

.controller('TmsOrderCtrl', ['$rootScope', '$scope', '$modal','$timeout', 'FileUploader', 'QiniuService','WaybillService',function ($rootScope, $scope, $modal, $timeout,FileUploader, QiniuService, WaybillService) {

    // 提车 交车运输方式
    $scope.checkStatus = [{
        code: 1,
        name: '不通过'
    },{
        code: 2,
        name: '通过'
    }];

    // 异常类型
    $scope.errorMsg = [{
        code: 10,
        name: '司机本人照片尚未采集'
    },{
        code: 20,
        name: '交车照片模糊'
    },{
        code: 30,
        name: '单据照片模糊'
    },{
        code: 40,
        name: '合影照片模糊'
    }];
     $scope.selectData = [
         {
             value : '20',
             text  : '已交车'
         },{
             value : '30',
             text  : '已完成'
         },{
             value : '40',
             text  : '未回单'
         }
     ];

    // 间隔时间
    $scope.errorInfo = {
        errorTag: ''
    };

    // 异常对象
    $scope.deliveryIssue = {
        waybillId: '',
        deliveryId: '',
        auditResultId: '',
        auditResult: '',
        issueTypeId: '',
        issueTypeContent: '',
        issueComment: '',
        disposalTypeId: '',
        disposalContent: '',
        queueTime: 12,
        operatorId: 14,
        disposalTypeWarningId: '',
        disposalWarningContent: '警告',
        disposalTypeForbiddenId: '',
        disposalForbiddenContent: '不可排队',
        disposalTypeWarningCheck: true,
        disposalTypeForbiddenCheck: false
    };

    // 查询条件
    $scope.orderInfo = {
        orderCode: '',
        self:'',
        beginDate: '',
        endDate: ''
    };

    $scope.orderList = [];

    // 运单附件
    $scope.attach = [];
    $scope.attachs = [];

    // 运单附件对象
    $scope.waybillAttach = {
        image: '',
        type: '',
        picHtml:''
    };

    // 订单详细信息
    var showInfoModal = $modal({scope: $scope, title: '交车审核', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/components/tms-order-pic-view.html', show: false});
    var showCheckTimeModal = $modal({scope: $scope, title: '设置可排队时间', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/components/tms-check-time-view.html', show: false});
    var showErrorModal = $modal({scope: $scope, title: '异常登记', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/components/tms-error-view.html', show: false});
    var showDisposeModal = $modal({scope: $scope, title: '处理办法', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/components/tms-dispose-view.html', show: false});


    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            if ($scope.orderInfo.beginDate!= null && $scope.orderInfo.beginDate != null){
                if ((+$scope.orderInfo.endDate) - (+$scope.orderInfo.beginDate) < 0) {
                    $rootScope.hycadmin.toast({
                        title: '交车开始时间不能大于结束时间',
                        timeOut: 3000
                    });
                    return;
                }
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        WaybillService.listDelivery({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            orderCode:$scope.orderInfo.orderCode,
            waybillStatus: $('#tms-select option:selected' ).val() || '20',
            beginDate: $scope.orderInfo.beginDate == ''?"": typeof ($scope.orderInfo.beginDate) == 'string'?$scope.orderInfo.beginDate : $scope.orderInfo.beginDate.format("yyyy-MM-dd 00:00:00"),
            endDate: $scope.orderInfo.endDate == ''?"": typeof ($scope.orderInfo.endDate) == 'string'?$scope.orderInfo.endDate : $scope.orderInfo.endDate.format("yyyy-MM-dd 23:59:59")
        }).success(function (result) {
            if (result.success) {
                $scope.orderList = result.data.dWaybillList;
                angular.forEach($scope.orderList, function (item) {
                     item.statusText = Tools.getDWaybillStatusText(item.status);
                     item.deliveryCheckStatusText = Tools.getDeliveryCheckStatusText(item.deliveryCheckStatus);
                     item.isSelfText = Tools.getIsSelfText(item.self);
                });
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };


    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    $scope.clearDeliveryIssue = function () {
        $scope.deliveryIssue = {
            waybillId: '',
            deliveryId: '',
            auditResultId: '',
            auditResult: '',
            issueTypeId: '',
            issueTypeContent: '',
            issueComment: '',
            disposalTypeId: '',
            disposalContent: '',
            queueTime: 12,
            disposalTypeWarningId: '',
            disposalWarningContent: '警告',
            disposalTypeForbiddenId: '',
            disposalForbiddenContent: '不可排队',
            disposalTypeWarningCheck: true,
            disposalTypeForbiddenCheck: false
        };
    };

    $scope.showCheckTimeDlg = function () {
        showCheckTimeModal.$promise.then(showCheckTimeModal.show);
        $scope.errorInfo.errorTag = false;
        $scope.deliveryIssue.queueTime = 12;
        $scope.deliveryIssue.auditResultId = Tools.getDeliveryAuditCode.getPassCode();
        $scope.deliveryIssue.auditResult = Tools.getDeliveryAuditName($scope.deliveryIssue.auditResultId);
    };

    $scope.showErrorDlg = function () {
        $scope.deliveryIssue.issueTypeId = '';
        $scope.deliveryIssue.issueComment = '';
        showErrorModal.$promise.then(showErrorModal.show);
    };

    $scope.showDisposeDlg = function () {
        if ($scope.deliveryIssue.issueTypeId == '') {
            layer.msg('异常原因不能为空');
            return false;
        } else if ($scope.deliveryIssue.issueComment.length >=100) {
            layer.msg('备注信息不能超过100字');
            return false;
        }
        $scope.deliveryIssue.issueTypeContent = Tools.getDeliveryErrorText($scope.deliveryIssue.issueTypeId);
        showErrorModal.$promise.then(showErrorModal.hide);
        showDisposeModal.$promise.then(showDisposeModal.show);
    };

    $scope.showLastStep = function () {
        showDisposeModal.$promise.then(showDisposeModal.hide);
        showErrorModal.$promise.then(showErrorModal.show);
    };

    $scope.deliveryIssueNext = function () {
        if (!$scope.deliveryIssue.disposalTypeWarningCheck && !$scope.deliveryIssue.disposalTypeForbiddenCheck) {
            layer.msg('请选择异常处理办法');
            return false;
        } else if ($scope.deliveryIssue.disposalTypeWarningCheck && !$scope.deliveryIssue.disposalTypeForbiddenCheck) {
            $scope.deliveryIssue.queueTime = 12;
            showCheckTimeModal.$promise.then(showCheckTimeModal.show);
            $scope.deliveryIssue.auditResultId = Tools.getDeliveryAuditCode.getApproveQueueCode();
            $scope.deliveryIssue.auditResult = Tools.getDeliveryAuditName($scope.deliveryIssue.auditResultId);
            $scope.deliveryIssue.disposalTypeId = Tools.getDeliveryIssueDisposalTypeCode.getPassCode();
            $scope.deliveryIssue.disposalContent = Tools.getDeliveryIssueDisposalTypeName($scope.deliveryIssue.disposalTypeId);
            $scope.errorInfo.errorTag = true;
        } else {
            $scope.deliveryIssue.auditResultId = Tools.getDeliveryAuditCode.getForbiddenQueueCode();
            $scope.deliveryIssue.auditResult = Tools.getDeliveryAuditName($scope.deliveryIssue.auditResultId);
            $scope.deliveryIssue.disposalTypeId = Tools.getDeliveryIssueDisposalTypeCode.getForbiddenQueueCode();
            $scope.deliveryIssue.disposalContent = Tools.getDeliveryIssueDisposalTypeName($scope.deliveryIssue.disposalTypeId);
            showDisposeModal.$promise.then(showDisposeModal.hide);
            showInfoModal.$promise.then(showInfoModal.hide());
            $scope.saveCheckPhoto();
        }
    };

    // 图片预览
    $scope.showModel = function (orderInfo) {
        showInfoModal.$promise.then(showInfoModal.show);
        $scope.deliveryIssue.waybillId = orderInfo.id;
        $scope.uploadImgs();
        WaybillService.orderlistInfo(orderInfo.id).success(function (result) {
            if (result.success) {
                $scope.DWaybillDetailVo = result.data;
                $scope.attach = $scope.DWaybillDetailVo.deliverPics;
                $scope.deliveryIssue.deliveryId = $scope.DWaybillDetailVo.deliveryID;
                $scope.DWaybillDetailVo.deliveryPicHtml = '<img src="' + $scope.DWaybillDetailVo.driverAvatarKey + '" style="width: 150px; z-index: 0; cursor: pointer;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')">';
                // 实际在途时间
                var msTime = new Date($scope.DWaybillDetailVo.deliveryTime).getTime() - new Date($scope.DWaybillDetailVo.departTime).getTime();// 交车时间 - 发车时间

                $scope.DWaybillDetailVo.hours = Math.ceil(msTime/(24*3600*1000))*24;
                // 标准在途时间
                $scope.DWaybillDetailVo.bHours = Math.ceil($scope.DWaybillDetailVo.distance/550)*24;// 公里数

                $scope.DWaybillDetailVo.isRed =  parseInt($scope.DWaybillDetailVo.bHours) < parseInt($scope.DWaybillDetailVo.hours) ? true: false;

                if ($scope.attach != null && $scope.attach.length > 0) {
                    angular.forEach($scope.attach, function (item) {
                        item.picHtml = '<img src="' + item.picKey + '" style="width: 195px; height: 180px; z-index: 0; cursor: pointer; padding: 3px;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')" ng-click="showBigImg(' + item.picKey + ')">';
                    });
                }else {
                    for (var i = 0; i < 3; i++) {
                        $scope.waybillAttach.category = 30;
                        if (i == 0) {
                            $scope.waybillAttach.type = Tools.getAttachTypeEnum.getDeliverPhoto();
                        } else if(i==1){
                            $scope.waybillAttach.type = Tools.getAttachTypeEnum.getUnionPhoto();
                        }else{
                            $scope.waybillAttach.type = Tools.getAttachTypeEnum.getDeliverBill();
                        }
                        $scope.waybillAttach.picHtml = '<img src="' + $scope.waybillAttach.picKey + '" style="width: 195px; height: 180px; z-index: 0; padding: 3px;" ng-click="showBigImg(' + $scope.waybillAttach.picKey + ')">';
                        $scope.attach.push($scope.waybillAttach);
                        // 清空对象
                        cleanAttach();
                    }
                }


            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 加载订单列表数据
    $scope.loadData('load');

    $scope.clearQuery = function () {
        $scope.orderInfo = {
            orderCode: '',
            self:'',
            beginDate: '',
            endDate: ''
        };
        $('#tms-select option' ).eq(0).attr('selected','selected').siblings().removeAttr('selected');
        $scope.loadData('load');
    };

    // 清空附件对象
    function cleanAttach() {
        $scope.waybillAttach = {
            image: '',
            type: '',
            picHtml:''

        }
    }

    // 审核
    $scope.saveCheckPhoto = function () {
        // 校验排队间隔时间
        if (!Tools.isNumber($scope.deliveryIssue.queueTime)) {
            layer.msg('排队间隔时间只能输入正整数');
            return;
        } else if ($scope.deliveryIssue.queueTime >24 || $scope.deliveryIssue.queueTime < 1) {
            layer.msg('排队间隔时间只能输入1~24');
            return;
        }
        $scope.deliveryIssue.attachs = JSON.stringify($scope.attachs);
        WaybillService.checkDelivery($scope.deliveryIssue).success(function (result) {
            if (result.success) {
                layer.msg('数据审核成功');
                showCheckTimeModal.$promise.then(showCheckTimeModal.hide);
                showInfoModal.$promise.then(showInfoModal.hide());
                if ($scope.errorInfo.errorTag) {
                    showDisposeModal.$promise.then(showDisposeModal.hide);
                }
                $scope.loadData('load');
            } else {
                layer.msg(result.message | '数据审核异常');
            }
        });
    };



    $scope.uploadImgs = function () {
        var uploader = $scope.uploader = null;
        QiniuService.getUploadQiniuToken()
            .success(function (result) {
                if (result.success) {
                    // 交车照片
                    var imgKey = null;
                    var uploader = $scope.uploader = new FileUploader({
                        url: 'http://upload.qiniu.com/',
                        formData: [{
                            token: result.data
                        }],
                        queueLimit: 1,
                        autoUpload: true
                    });

                    uploader.filters.push({
                        name: 'file',
                        fn: function(item /*{File|FileLikeObject}*/, options) {
                            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                        }
                    });
                    uploader.onSuccessItem = function(fileItem, response, status, headers) {
                        $rootScope.hycadmin.loading({
                            title: '数据处理中...'
                        });
                        QiniuService.getDownloadQiniuTicket({
                            key: response.key
                        }).success(function(result){
                            if (result.success) {
                                if ($scope.attach != null) {
                                    angular.forEach($scope.attach,function (item) {
                                        if (item.type == 3010) {
                                            item.picKey = result.data;
                                            item.picHtml = '<img src="' + item.picKey + '" style="width: 195px; height: 180px; z-index: 0; cursor: pointer; padding: 3px;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')" ng-click="showBigImg(' + item.picKey + ')">';
                                            $scope.waybillAttach.image = response.key;
                                            $scope.waybillAttach.type = 3010;
                                            $scope.attachs.push($scope.waybillAttach);
                                            // 清空对象
                                            cleanAttach();
                                        }
                                    });
                                }
                            }
                        }).finally(function() {
                            $rootScope.hycadmin.loading.hide();
                        });
                    };

                    // 提车照片
                    var imgKey2 = null;
                    var uploader2 = $scope.uploader2 = new FileUploader({
                        url: 'http://upload.qiniu.com/',
                        formData: [{
                            token: result.data
                        }],
                        queueLimit: 1,
                        autoUpload: true
                    });

                    uploader2.filters.push({
                        name: 'file',
                        fn: function(item /*{File|FileLikeObject}*/, options) {
                            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                        }
                    });
                    uploader2.onSuccessItem = function(fileItem, response, status, headers) {
                        $rootScope.hycadmin.loading({
                            title: '数据处理中...'
                        });
                        QiniuService.getDownloadQiniuTicket({
                            key: response.key
                        }).success(function(result){
                            if (result.success) {
                                if ($scope.attach != null) {
                                    angular.forEach($scope.attach, function (item) {
                                        if (item.type == 3020) {
                                            item.picKey = result.data;
                                            item.picHtml = '<img src="' + item.picKey + '" style="width: 195px; height: 180px; z-index: 0; cursor: pointer; padding: 3px;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')" ng-click="showBigImg(' + item.picKey + ')">';
                                            $scope.waybillAttach.image = response.key;
                                            $scope.waybillAttach.type = 3020;
                                            $scope.attachs.push($scope.waybillAttach);
                                            // 清空对象
                                            cleanAttach();
                                        }
                                    });
                                }
                            }
                        }).finally(function(){
                            $rootScope.hycadmin.loading.hide();
                        });
                    };

                    // 交车单据照片
                    var imgKey3 = null;
                    var uploader3 = $scope.uploader3 = new FileUploader({
                        url: 'http://upload.qiniu.com/',
                        formData: [{
                            token: result.data
                        }],
                        queueLimit: 1,
                        autoUpload: true
                    });

                    uploader3.filters.push({
                        name: 'file',
                        fn: function(item /*{File|FileLikeObject}*/, options) {
                            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                            return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                        }
                    });
                    uploader3.onSuccessItem = function(fileItem, response, status, headers) {
                        $rootScope.hycadmin.loading({
                            title: '数据处理中...'
                        });
                        QiniuService.getDownloadQiniuTicket({
                            key: response.key
                        }).success(function(result){
                            if (result.success) {
                                if ($scope.attach != null) {
                                    angular.forEach($scope.attach, function (item) {
                                        if (item.type == 3030) {
                                            item.picKey = result.data;
                                            item.picHtml = '<img src="' + item.picKey + '" style="width: 195px; height: 180px; z-index: 0; cursor: pointer; padding: 3px;" onerror="Tools.onLoadImgErrorCallback(this, \'/image/truck-default-logo.png\')" ng-click="showBigImg(' + item.picKey + ')">';
                                            $scope.waybillAttach.image = response.key;
                                            $scope.waybillAttach.type = 3030;
                                            $scope.attachs.push($scope.waybillAttach);
                                            // 清空对象
                                            cleanAttach();
                                        }
                                    });
                                }
                            }
                        }).finally(function(){
                            $rootScope.hycadmin.loading.hide();
                        });
                    };


                }
            })
    };

}])

.controller('TmsOrderUnlockCtrl', ['$rootScope', '$scope', '$modal','$timeout','WaybillService',function ($rootScope, $scope, $modal, $timeout, WaybillService) {
    // 查询条件
    $scope.orderInfo = {
        orderCode: ''
    };

    $scope.orderList = [];
    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

// 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        WaybillService.listintransit({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            orderCode:$scope.orderInfo.orderCode
        }).success(function (result) {
            if (result.success) {
                $scope.orderList = result.data.dWaybillList;
                angular.forEach($scope.orderList, function (item) {
                    item.statusText = Tools.getDWaybillStatusText(item.status);
                    item.checkLocalPicText = Tools.getLockStatusText(item.isCheckLocalPic);
                })
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };


    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

// 加载订单列表数据
    $scope.loadData('load');

    $scope.clearQuery = function () {
        $scope.orderInfo = {
            orderCode: ''
        };
        $scope.loadData('load');
    };

    // 图片预览
    $scope.changeLockPicStatus = function (orderInfo) {
        var lockStatus = orderInfo.isCheckLocalPic;
        if(lockStatus==0){
            WaybillService.openCheckPic({
                id:orderInfo.id
            }).success(function (result) {
                if (result.success) {
                    $rootScope.hycadmin.toast({
                        title: '解锁选取相册',
                        timeOut: 3000
                    });
                    $scope.loadData('load');
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        }else if(lockStatus==1){
            WaybillService.closeCheckPic({
                id:orderInfo.id
            }).success(function (result) {
                if (result.success) {
                    $rootScope.hycadmin.toast({
                        title: '锁定选取相册',
                        timeOut: 3000
                    });
                    $scope.loadData('load');
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        }


    }
}])